<template>
  <div class="schedule-management">
    <h2>{{ $t('message.scheduleManagement') }}</h2>
    
    <div class="schedule-actions">
      <el-button type="primary" @click="openAddScheduleDialog">{{ $t('message.addSchedule') }}</el-button>
    </div>
    
    <el-table
      :data="schedules"
      style="width: 100%"
      :default-sort="{ prop: 'startTime', order: 'ascending' }"
    >
      <el-table-column prop="courseName" :label="$t('message.courseName')" width="180" align="left" header-align="left" />
      <el-table-column prop="teacherName" :label="$t('message.teacher')" width="120" align="left" header-align="left" />
      <el-table-column prop="startTime" :label="$t('message.startTime')" width="150" align="left" header-align="left">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" :label="$t('message.endTime')" width="150" align="left" header-align="left">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="maxParticipants" :label="$t('message.maxParticipants')" width="130" align="left" header-align="left" />
      <el-table-column prop="status" :label="$t('message.status')" width="120" align="left" header-align="left">
        <template #default="scope">
          <el-tag 
            :type="getStatusType(scope.row.status)"
            disable-transitions
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="250" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="editSchedule(scope.row)">{{ $t('message.edit') }}</el-button>
          <el-button 
            size="small" 
            :type="scope.row.status === 'SCHEDULED' ? 'warning' : 'primary'"
            @click="toggleScheduleStatus(scope.row)"
          >
            {{ getToggleText(scope.row.status) }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteSchedule(scope.row.scheduleId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑排课对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="130px">
        <el-form-item :label="$t('message.course')" prop="courseId">
          <el-select 
            v-model="scheduleForm.courseId" 
            :placeholder="$t('message.pleaseSelectCourse')" 
            style="width: 100%"
            @change="onCourseChange"
          >
            <el-option
              v-for="course in courses"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.teacher')" prop="teacherId">
          <el-select v-model="scheduleForm.teacherId" :placeholder="$t('message.pleaseSelectTeacher')" style="width: 100%">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.userId"
              :label="teacher.username"
              :value="teacher.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.startTime')" prop="startTime">
          <el-date-picker
            v-model="scheduleForm.startTime"
            type="datetime"
            :placeholder="$t('message.pleaseSelectStartTime')"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('message.endTime')" prop="endTime">
          <el-date-picker
            v-model="scheduleForm.endTime"
            type="datetime"
            :placeholder="$t('message.pleaseSelectEndTime')"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('message.maxParticipants')" prop="maxParticipants">
          <el-input-number 
            v-model="scheduleForm.maxParticipants" 
            :min="1" 
            :max="100"
            :placeholder="$t('message.pleaseEnterMaxParticipants')"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('message.status')" prop="status">
          <el-select v-model="scheduleForm.status" :placeholder="$t('message.pleaseSelectStatus')" style="width: 100%">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveSchedule">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'ScheduleManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 排课数据
    const schedules = ref([]);
    const courses = ref([]);
    const teachers = ref([]);
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    
    // 表单数据
    const scheduleForm = reactive({
      scheduleId: '',
      courseId: '',
      teacherId: '',
      startTime: '',
      endTime: '',
      maxParticipants: 1,
      status: 'SCHEDULED'
    });
    
    const scheduleFormRef = ref();
    
    // 选项数据
    const statusOptions = ref([
      { value: 'SCHEDULED', label: t('message.scheduled') },
      { value: 'IN_PROGRESS', label: t('message.inProgress') },
      { value: 'COMPLETED', label: t('message.completed') },
      { value: 'CANCELLED', label: t('message.cancelled') }
    ]);
    
    // 表单验证规则
    const scheduleRules = {
      courseId: [
        { required: true, message: t('message.pleaseSelectCourse'), trigger: 'change' }
      ],
      teacherId: [
        { required: true, message: t('message.pleaseSelectTeacher'), trigger: 'change' }
      ],
      startTime: [
        { required: true, message: t('message.pleaseSelectStartTime'), trigger: 'change' }
      ],
      endTime: [
        { required: true, message: t('message.pleaseSelectEndTime'), trigger: 'change' }
      ],
      maxParticipants: [
        { required: true, message: t('message.pleaseEnterMaxParticipants'), trigger: 'blur' }
      ]
    };
    
    // 获取排课列表
    const loadSchedules = async () => {
      try {
        // 确定是管理员还是教师获取排课
        const isTeacher = authStore.user?.roleId === 'TEACHER';
        const apiUrl = isTeacher 
          ? `/api/teacher/schedules` 
          : `/api/admin/schedules`;
        
        const response = await fetch(apiUrl, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          // 添加课程名称和教师名称
          schedules.value = data.map(schedule => {
            // 这里应该从相关的课程和用户数据中获取名称
            const course = courses.value.find(c => c.courseId === schedule.courseId);
            const teacher = teachers.value.find(t => t.userId === schedule.teacherId);
            
            return {
              ...schedule,
              courseName: course ? course.courseName : schedule.courseId,
              teacherName: teacher ? teacher.username : schedule.teacherId
            };
          });
        } else {
          ElMessage.error(t('message.failedToLoadSchedules'));
        }
      } catch (error) {
        console.error('Error loading schedules:', error);
        ElMessage.error(t('message.failedToLoadSchedules'));
      }
    };
    
    // 获取课程列表
    const loadCourses = async () => {
      try {
        const isTeacher = authStore.user?.roleId === 'TEACHER';
        const apiUrl = isTeacher 
          ? `/api/teacher/courses` 
          : `/api/admin/courses`;
        
        const response = await fetch(apiUrl, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          courses.value = await response.json();
        }
      } catch (error) {
        console.error('Error loading courses:', error);
      }
    };
    
    // 获取教师列表
    const loadTeachers = async () => {
      try {
        const response = await fetch('/api/admin/users/teachers', {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          teachers.value = await response.json();
        }
      } catch (error) {
        console.error('Error loading teachers:', error);
      }
    };
    
    // 打开添加排课对话框
    const openAddScheduleDialog = () => {
      isEdit.value = false;
      dialogTitle.value = t('message.addSchedule');
      resetForm();
      // 如果是教师，自动设置为当前教师
      if (authStore.user?.roleId === 'TEACHER') {
        scheduleForm.teacherId = authStore.user.userId;
      }
      dialogVisible.value = true;
    };
    
    // 编辑排课
    const editSchedule = (schedule) => {
      isEdit.value = true;
      dialogTitle.value = t('message.editSchedule');
      // 复制排课数据到表单
      Object.assign(scheduleForm, schedule);
      dialogVisible.value = true;
    };
    
    // 删除排课
    const deleteSchedule = async (scheduleId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteSchedule'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/schedules/${scheduleId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteScheduleSuccess'));
          loadSchedules(); // 重新加载排课
        } else {
          ElMessage.error(t('message.deleteScheduleFailed'));
        }
      } catch (error) {
        console.error('Error deleting schedule:', error);
      }
    };
    
    // 切换排课状态
    const toggleScheduleStatus = async (schedule) => {
      try {
        // 根据当前状态决定下一个状态
        let newStatus = '';
        let actionText = '';
        
        switch (schedule.status) {
          case 'SCHEDULED':
            newStatus = 'IN_PROGRESS';
            actionText = t('message.start');
            break;
          case 'IN_PROGRESS':
            newStatus = 'COMPLETED';
            actionText = t('message.complete');
            break;
          case 'COMPLETED':
            newStatus = 'SCHEDULED';
            actionText = t('message.reschedule');
            break;
          case 'CANCELLED':
            newStatus = 'SCHEDULED';
            actionText = t('message.reactivate');
            break;
          default:
            newStatus = 'SCHEDULED';
            actionText = t('message.activate');
        }
        
        await ElMessageBox.confirm(
          `${actionText} ${t('message.scheduleConfirm')}?`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        // 更新排课状态
        const response = await fetch(`/api/admin/schedules/${schedule.scheduleId}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ ...schedule, status: newStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadSchedules(); // 重新加载排课
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error toggling schedule status:', error);
      }
    };
    
    // 保存排课
    const saveSchedule = async () => {
      try {
        await scheduleFormRef.value.validate();
        
        // 验证开始时间不能晚于结束时间
        if (new Date(scheduleForm.startTime) >= new Date(scheduleForm.endTime)) {
          ElMessage.error(t('message.startTimeBeforeEndTime'));
          return;
        }
        
        let response;
        if (isEdit.value) {
          // 更新排课
          response = await fetch(`/api/admin/schedules/${scheduleForm.scheduleId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(scheduleForm)
          });
        } else {
          // 创建排课
          response = await fetch('/api/admin/schedules', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(scheduleForm)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateScheduleSuccess') : t('message.addScheduleSuccess'));
          dialogVisible.value = false;
          loadSchedules(); // 重新加载排课
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateScheduleFailed') : t('message.addScheduleFailed')));
        }
      } catch (error) {
        console.error('Error saving schedule:', error);
        ElMessage.error(isEdit.value ? t('message.updateScheduleFailed') : t('message.addScheduleFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(scheduleForm, {
        scheduleId: '',
        courseId: '',
        teacherId: authStore.user?.roleId === 'TEACHER' ? authStore.user.userId : '',
        startTime: '',
        endTime: '',
        maxParticipants: 1,
        status: 'SCHEDULED'
      });
    };
    
    // 课程选择变化时的处理
    const onCourseChange = (courseId) => {
      // 可以根据选择的课程自动填充相关信息
      const course = courses.value.find(c => c.courseId === courseId);
      if (course) {
        // 可以自动设置教师（如果是教师用户）
        if (!scheduleForm.teacherId && authStore.user?.roleId === 'TEACHER') {
          scheduleForm.teacherId = authStore.user.userId;
        }
      }
    };
    
    // 获取状态类型（用于标签样式）
    const getStatusType = (status) => {
      switch (status) {
        case 'SCHEDULED': return 'info';
        case 'IN_PROGRESS': return 'warning';
        case 'COMPLETED': return 'success';
        case 'CANCELLED': return 'danger';
        default: return 'info';
      }
    };
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'SCHEDULED': return t('message.scheduled');
        case 'IN_PROGRESS': return t('message.inProgress');
        case 'COMPLETED': return t('message.completed');
        case 'CANCELLED': return t('message.cancelled');
        default: return status;
      }
    };
    
    // 获取切换状态按钮文本
    const getToggleText = (status) => {
      switch (status) {
        case 'SCHEDULED': return t('message.start');
        case 'IN_PROGRESS': return t('message.complete');
        case 'COMPLETED': return t('message.reschedule');
        case 'CANCELLED': return t('message.reactivate');
        default: return t('message.update');
      }
    };
    
    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '';
      const date = new Date(dateTimeStr);
      return date.toLocaleString();
    };
    
    onMounted(async () => {
      await Promise.all([
        loadCourses(),
        loadTeachers()
      ]);
      loadSchedules();
    });
    
    return {
      schedules,
      courses,
      teachers,
      dialogVisible,
      dialogTitle,
      scheduleForm,
      scheduleFormRef,
      scheduleRules,
      statusOptions,
      openAddScheduleDialog,
      editSchedule,
      deleteSchedule,
      toggleScheduleStatus,
      saveSchedule,
      onCourseChange,
      getStatusType,
      getStatusText,
      getToggleText,
      formatDateTime
    };
  }
};
</script>

<style scoped>
.schedule-management {
  padding: 20px;
}

.schedule-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>